import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,asyncRoutes,constantRoutes ,anyRoutes} from '@/router'
import router from '../../router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles:[],
    routes:[],
    buttons:[],
    // 存储异步路由：根据不同角色展示不同的路由
    asyncRoutes:[],
    //存储用户访问的全部路由
    allRoutes:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  //存储用户信息
  SET_USERINFO: (state, userInfo) => {
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    state.roles = userInfo.roles
    state.routes = userInfo.routes
    state.buttons = userInfo.buttons
  },
  //计算最终路由
  SET_ROUTES:(state,asyncRoutes) => {
    state.asyncRoutes=asyncRoutes
    // 所有路由存储到state.allRoutes
    state.allRoutes= constantRoutes.concat(state.asyncRoutes,anyRoutes)
    // 路由器添加新的路由
    router.addRoutes(state.allRoutes)
  }

}
//计算不同用户的异步路由
function computedAsyncRoutes(asyncroutes,routes){

return  asyncroutes.filter((item) => {
    if(routes.indexOf(item.name)!=-1){
      // 递归，算出2,3..级路由
      if(item.children){
        item.children=computedAsyncRoutes(item.children,routes)
      }
      return true
    }
  })
}
const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    let result = await login({ username: username.trim(), password: password })
    if (result.code == 20000) {
      commit('SET_TOKEN', result.data.token)
      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     const { data } = response
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        //存储用户信息:name、avatar、buttons、roles、routes
        commit('SET_USERINFO', data)
        commit('SET_ROUTES',computedAsyncRoutes(asyncRoutes,data.routes))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  async logout({ commit, state }) {
    let result = await logout(state.token)
    if (result.code == 20000) {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
    } else {
      new Promise.reject(new Error('fail'))
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

